<!--suppress HtmlDeprecatedAttribute -->
<template>
  <el-dialog :visible.sync="dialogVisible" :append-to-body="true" :title="dialogText" width="70%">
    <el-form ref="form" :model="formData" label-width="80px" :disabled="loading">
      <el-row :gutter="40" style="margin-bottom: 16px">
        <el-col :span="24" align="left">
          <span class="title">订单信息</span>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item prop="id" label="订单编号">
            <el-input v-model="formData.id" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="name" label="商品">
            <el-input v-model="formData.name" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="count" label="数量">
            <el-input v-model="formData.count" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="goodsPrice" label="商品金额">
            <el-input v-model="formData['goodsPrice']" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="freight" label="运费">
            <el-input v-model="formData.freight" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="freightInsu" label="运费险">
            <el-input v-model="formData['freightInsu']" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="totalIntegral" label="积分">
            <el-input v-model="formData.totalIntegral" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="price" label="总金额">
            <el-input v-model="formData.price" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="state" label="状态">
            <el-input v-model="formData.state" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="payType" label="支付方式">
            <el-input v-model="formData['payType']" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="payId" label="支付单号">
            <el-input v-model="formData['payId']" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="priceTime" label="支付时间">
            <el-input v-model="formData.priceTime" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="endAddressDesc" label="收货地址">
            <el-input v-model="formData['endAddressDesc']" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="message" label="留言">
            <el-input v-model="formData['message']" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="orderInfoMoreFlag">
          <el-form-item prop="remark" label="备注">
            <el-input v-model="formData['remark']" :readonly="true"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
       <el-col :span="24" align="right">
         <el-button type="info" size="mini" @click="handleOrderInfoMoreFlag"
         :icon="orderInfoMoreIcon">{{orderInfoMoreText}}</el-button>
       </el-col>
      </el-row>
    </el-form>
    <el-form ref="submitForm" :model="submitForm" label-width="80px" :disabled="loading" :rules="submitFormRuler">
      <el-row :gutter="40" style="margin-bottom: 16px">
        <el-col :span="24" align="left">
          <span class="title">发货信息</span>
        </el-col>
      </el-row>
      <el-row :gutter="40" style="margin-bottom: 16px">
        <el-col :span="8">
          <el-form-item prop="addressId" label="发货地址">
            <el-select v-model="submitForm['addressId']" :placeholder="addressPlaceholder"
                       :disabled="addressLoading">
              <el-option v-for="item in storeAddress" :key="item.id" :label="item.label"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="logisticsNumber" label="物流编号">
            <el-input v-model="submitForm['logisticsNumber']" @change="freshLogisticsCode"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="logisticsCode" label="物流公司">
            <el-select v-model="submitForm['logisticsCode']" :placeholder="logisticsCodePlaceholder"
                       :disabled="logisticsCodeLoading">
              <el-option v-for="item in logisticsCodeData" :key="item.key" :label="item.value"
                         :value="item.key"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button @click="resetDialog" v-if="addType">重置</el-button>
        <el-button @click="resetChangeDialog" v-if="changeType">重置</el-button>
        <el-button @click="handleCancelDelivery" v-if="changeType"
                   :disabled="loading" :loading="cancelLoading">取消发货</el-button>
        <el-button type="primary" @click="handleDeliveryGood" v-if="addType"
                   :disabled="loading" :loading="submitLoading">发货</el-button>
        <el-button type="primary" @click="handleChangeDeliveryGood" v-if="changeType"
                   :disabled="loading" :loading="submitLoading">提交</el-button>
      </span>
  </el-dialog>
</template>

<script>
import { ResultCode } from '@/constants/constants'
import { queryOrderDetailByIdStore } from '@/api/ApiOrderDetail'
import { formatTime } from '@/utils/ConvertData'
import { queryAllStoreAddress, queryDefaultStoreAddress } from '@/api/ApiStoreAddress'
import {
  cancelDeliverByOrderIds,
  changeDeliverGoodByOrderIds,
  deliverGoodByOrderIds,
  orderDistinguish
} from '@/api/ApiGoodDeliver'
import { DeliverGoodDTO } from '@/api/entity/DeliverGoodDTO'
import { DeliverGoodChangeDTO } from '@/api/entity/DeliverGoodChangeDTO'

export default {
  name: 'DeliveryDialog',
  props: {
    visible: {
      required: true,
      type: Boolean
    },
    orderId: {
      required: true,
      type: [String, Number]
    },
    type: {
      required: false,
      type: String,
      default: 'add'
    }
  },
  model: {
    prop: 'visible',
    event: 'visible'
  },
  data () {
    return {
      dialogVisible: false,
      formData: {
        id: 222
      },
      queryLoading: false,
      submitLoading: false,
      cancelLoading: false,
      addressLoading: false,
      logisticsCodeLoading: false,
      orderInfoMoreFlag: false,
      // 上传的数据
      submitForm: {
        addressId: '',
        logisticsNumber: '',
        logisticsCode: ''
      },
      submitFormRuler: {
        addressId: [{
          required: true,
          message: '发货地址不能为空',
          trigger: 'blur'
        }],
        logisticsNumber: [{
          required: true,
          message: '物流编号不能为空',
          trigger: 'blur'
        }, {
          min: 6,
          message: '物流编号长度不能小于6位',
          trigger: 'blur'
        }, {
          max: 24,
          message: '物流编号长度不能大于24位',
          trigger: 'blur'
        }],
        logisticsCode: [{
          required: true,
          message: '物流公司不能为空',
          trigger: 'change'
        }]
      },
      storeAddress: [],
      logisticsCodeData: []
    }
  },
  computed: {
    dialogText () {
      return this.type === 'add' ? '发货' : '编辑'
    },
    loading () {
      return this.queryLoading || this.submitLoading || this.cancelLoading
    },
    orderInfoMoreText () {
      return this.orderInfoMoreFlag ? '收回' : '更多'
    },
    orderInfoMoreIcon () {
      return this.orderInfoMoreFlag ? '收回' : '更多'
    },
    addressPlaceholder () {
      return this.addressLoading ? '加载中' : '请选择发货地址'
    },
    logisticsCodePlaceholder () {
      return this.logisticsCodeLoading ? '加载中' : '请选择物流公司'
    },
    addType () {
      return this.type === 'add'
    },
    changeType () {
      return this.type === 'change'
    }
  },
  methods: {
    handleOrderInfoMoreFlag () {
      this.orderInfoMoreFlag = !this.orderInfoMoreFlag
    },
    /**
       * 关闭对话框
       */
    closeDialog () {
      this.dialogVisible = false
    },
    /**
       * 退款
       */
    handleRefund () {
      this.$msgbox({
        title: '退款',
        message: '确定取款吗？',
        showCancelButton: true,
        confirmButtonText: '退款',
        cancelButtonText: '取消'
      }).then(action => {
        if (action === 'confirm') {
          this.$message.success('退款啦')
          this.refund()
        }
      })
    },
    /**
       * 转换数据
       */
    convertOrderDetail (item) {
      item.createTime = formatTime(item['createTime'])
      item.priceTime = formatTime(item['priceTime'])
      item.totalIntegral = item['integral']
      const list = item['list']
      if (list && typeof list === 'object') {
        item.name = list[0]['goodName'] + '|' + list[0]['subGoodName']
        item.count = 0
        list.forEach(sub => {
          item.count += sub.count
        })
      }
      return item
    },
    /**
     * 更新数据
     */
    refreshData () {
      this.queryLoading = true
      queryOrderDetailByIdStore(this.orderId, data => {
        if (data && data.code === ResultCode.OK) {
          this.formData = this.convertOrderDetail(data.object)
        }
      }, () => {
        this.queryLoading = false
      })
    },
    /**
     * 更新编辑状态数据
     */
    refreshChangeData () {
      this.queryLoading = true
      queryOrderDetailByIdStore(this.orderId, data => {
        if (data && data.code === ResultCode.OK) {
          data = data.object
          this.formData = this.convertOrderDetail(data)
          this.submitForm = {
            addressId: data['startAddressId'],
            logisticsNumber: data['logisticsNumber'],
            logisticsCode: data['logisticsCode']
          }
          this.freshLogisticsCode()
        }
      }, () => {
        this.queryLoading = false
      })
    },
    /**
     * 获取店铺用户所有地址
     */
    freshAddressData () {
      this.addressLoading = true
      queryAllStoreAddress(data => {
        if (data && data.code === ResultCode.OK) {
          const storeAddress = data.object
          const list = []
          if (storeAddress && typeof storeAddress === 'object') {
            storeAddress.forEach(item => {
              item = this.convertAddressToSelect(item)
              list.push(item)
            })
          }
          this.storeAddress = list
        }
      }, () => {
        this.addressLoading = false
      })
    },
    freshDefaultAddress () {
      queryDefaultStoreAddress(data => {
        if (data && data.code === ResultCode.OK) {
          const storeAddress = data.object
          if (storeAddress && storeAddress.id) {
            this.submitForm.addressId = storeAddress.id
          }
        }
      })
    },
    convertAddressToSelect (item) {
      if (!item) {
        return item
      }
      item['label'] = item['provinceName'] + item['cityName'] + item['countyName'] + item['detail']
      return item
    },
    /**
     * 物流单号更改时刷新物流公司
     */
    freshLogisticsCode () {
      const code = this.submitForm.logisticsNumber
      if (code && code.length > 0 && !this.logisticsCodeLoading) {
        if (code.length < 6) {
          return
        }
        this.logisticsCodeLoading = true
        orderDistinguish(code, data => {
          if (data && data.code === ResultCode.OK) {
            const d = data.object
            if (d && typeof d === 'object') {
              if (d.length === 0) {
                this.logisticsCodeData = []
                this.submitForm.logisticsCode = ''
              } else if (d.length === 1) {
                this.logisticsCodeData = d
                this.submitForm.logisticsCode = d[0].key
                this.$refs['submitForm'].validateField('logisticsCode')
              } else {
                this.logisticsCodeData = d
                this.submitForm.logisticsCode = ''
                this.$refs['submitForm'].validateField('logisticsCode')
              }
            }
          }
        }, () => {
          this.logisticsCodeLoading = false
        })
      }
    },
    /**
     * 清空参数
     */
    clearSubmitData () {
      this.submitForm = {
        addressId: '',
        logisticsNumber: '',
        logisticsCode: ''
      }
    },
    /**
     * 重置对话框
     */
    resetDialog () {
      this.refreshData()
      this.clearSubmitData()
      this.logisticsCodeData = []
    },
    /**
     * 重置修改状态对话框
     */
    resetChangeDialog () {
      this.refreshChangeData()
    },
    /**
     * 取消发货
     */
    handleCancelDelivery () {
      this.$confirm('你将要取消发货，取消后订单将恢复到待发货状态, 是否继续?', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.cancelLoading = true
        const params = [this.orderId]
        cancelDeliverByOrderIds(params, data => {
          if (data && data.code === ResultCode.OK) {
            this.$message.success('取消发货成功')
            this.$emit('change')
            this.dialogVisible = false
          }
        }, () => {
          this.cancelLoading = false
        })
      }).catch(() => {
      })
    },
    /**
     * 发货
     */
    handleDeliveryGood () {
      this.$refs.submitForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const params = DeliverGoodDTO.instance()
          params.setOrderId(this.orderId)
          params.setAddressId(this.submitForm.addressId)
          params.setLogisticsNumber(this.submitForm.logisticsNumber)
          params.setLogisticsCode(this.submitForm.logisticsCode)
          for (let i = 0; i < this.logisticsCodeData.length; i++) {
            if (this.logisticsCodeData[i].key === this.submitForm.logisticsCode) {
              const name = this.logisticsCodeData[i].value
              params.setLogisticsName(name)
            }
          }
          params.setLogisticsName()
          deliverGoodByOrderIds([params], data => {
            if (data && data.code === ResultCode.OK) {
              this.$message.success('发货成功')
              this.$emit('change')
              this.dialogVisible = false
            }
          }, () => {
            this.submitLoading = false
          })
        }
      })
    },
    /**
     * 修改发货信息
     */
    handleChangeDeliveryGood () {
      this.$refs.submitForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const params = DeliverGoodChangeDTO.instance()
          params.setOrderId(this.orderId)
          params.setAddressId(this.submitForm.addressId)
          params.setLogisticsNumber(this.submitForm.logisticsNumber)
          params.setLogisticsCode(this.submitForm.logisticsCode)
          for (let i = 0; i < this.logisticsCodeData.length; i++) {
            if (this.logisticsCodeData[i].key === this.submitForm.logisticsCode) {
              const name = this.logisticsCodeData[i].value
              params.setLogisticsName(name)
            }
          }
          params.setLogisticsName()
          changeDeliverGoodByOrderIds([params], data => {
            if (data && data.code === ResultCode.OK) {
              this.$message.success('修改发货信息成功')
              this.$emit('change')
              this.dialogVisible = false
            }
          }, () => {
            this.submitLoading = false
          })
        }
      })
    }
  },
  watch: {
    dialogVisible (val) {
      this.$emit('visible', val)
    },
    visible (val) {
      if (this.dialogVisible !== val) {
        this.dialogVisible = val
      }
    },
    orderId () {
      if (this.addType) {
        this.resetDialog()
      } else {
        this.resetChangeDialog()
      }
    },
    type () {
      if (this.addType) {
        this.resetDialog()
      } else {
        this.resetChangeDialog()
      }
    }
  },
  mounted () {
    this.freshAddressData()
    this.freshDefaultAddress()
  }
}
</script>

<style scoped lang="scss">

  .title{
    border-left: 4px solid blue;
    padding-left: 6px;
    font-weight: 600;
  }

</style>
